from django import template
import django.core.paginator
from django.utils import safestring

import core.url

register = template.Library()

@register.simple_tag
def paginator_nav(current_page, paginator, url):
  """Paginator navigation links
  Usage:
    {% paginator_nav paginator url %}
  
  Output:
    If there is only one page: no output
    else: 
      1 of n > >>
      < 2 of n > >>
      << < k of n > >>
      << < n-1 of n >
      << < n of n
  """
  try:
    current_page = int(current_page)
  except:
    return safestring.mark_safe(u'')
  if not isinstance(paginator, django.core.paginator.Paginator):
    return safestring.mark_safe(u'')
  if not isinstance(url, core.url.URL):
    return safestring.mark_safe(u'')
  if paginator.num_pages == 1:
    return u''
  bits = []
  if current_page > 2:
    url.addQueryData('page', 1)
    bits.append('<a href=%s>&lt;&lt;</a>' % url.toString())
  if current_page > 1:
    url.addQueryData('page', current_page - 1)
    bits.append('<a href=%s>&lt;</a>' % url.toString())
  bits.append('%s of %s' % (current_page, paginator.num_pages))
  if current_page < paginator.num_pages:
    url.addQueryData('page', current_page + 1)
    bits.append('<a href=%s>&gt;</a>' % url.toString())
  if current_page < paginator.num_pages - 1:
    url.addQueryData('page', paginator.num_pages)
    bits.append('<a href=%s>&gt;&gt;</a>' % url.toString())
  return safestring.mark_safe(u'&nbsp;'.join(bits))
